package com.learning.optimize.jdk.annotation;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.util.Arrays;

/**
 * ClassName: AnnotationReflect
 * Description: 注解反射
 * Date: 2018/7/18 15:19 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class AnnotationReflect {

    public static void main(String[] args) {
        test();
    }

    /**
     * 注解的反射
     */
    static void test() {
        Class<AnnotationClass> clazz = AnnotationClass.class;

        // 根据指定注解类型获取该注解
        GroupAnnotation annotation = clazz.getAnnotation(GroupAnnotation.class);
        System.out.println("GroupAnnotation: " + annotation);

        // 获取该元素上的所有注解，包含从父类继承
        Annotation[] annotations = clazz.getAnnotations();
        System.out.println("getAnnotations: " + Arrays.toString(annotations));

        // 获取该元素上的所有注解，但不包含继承！
        Annotation[] declaredAnnotations = clazz.getDeclaredAnnotations();
        System.out.println("getDeclaredAnnotations: " + Arrays.toString(declaredAnnotations));

        //判断注解CustomAnnotation是否在该元素上
        boolean annotationPresent = clazz.isAnnotationPresent(CustomAnnotation.class);
        System.out.println("isAnnotationPresent: " + annotationPresent);



        /*
        输出：
        GroupAnnotation: @com.learning.optimize.jdk.annotation.GroupAnnotation()
        getAnnotations: [@com.learning.optimize.jdk.annotation.CustomAnnotation(name=, names=[], value=0, showSupport=false), @com.learning.optimize.jdk.annotation.GroupAnnotation()]
        getDeclaredAnnotations: [@com.learning.optimize.jdk.annotation.GroupAnnotation()]
        isAnnotationPresent: true
        */
    }

    /**
     * JDK8:
     * 1、元注解@Repeatable
     * 2、新增的两种ElementType
     */
    static void test2() {

        // 可以用于标注类型参数 class D<@Parameter T> { }
        ElementType typeParameter = ElementType.TYPE_PARAMETER;

        // 用于标注任意类型(不包括class)
        ElementType typeUse = ElementType.TYPE_USE;
    }
}


@CustomAnnotation
@GroupAnnotation(value = 20, name = "Sam")
class AnnotationSuperClass {

}

@GroupAnnotation(20)
class AnnotationClass extends AnnotationSuperClass {

}
